package org.jeecg.modules.feeLpg.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.chargeLpg.service.IChargeLpgService;
import org.jeecg.modules.consumptionLpg.service.IConsumptionLpgService;
import org.jeecg.modules.feeLpg.entity.FeeLpg;
import org.jeecg.modules.feeLpg.service.IFeeLpgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Configuration
@EnableScheduling
@Slf4j
public class FeeLpgScheduled {

    private final IFeeLpgService feeLpgService;
    private final IConsumptionLpgService consumptionLpgService;
    private final IChargeLpgService chargeLpgService;

    @Autowired
    public FeeLpgScheduled(IFeeLpgService feeLpgService, IConsumptionLpgService consumptionLpgService, IChargeLpgService chargeLpgService) {
        this.feeLpgService = feeLpgService;
        this.consumptionLpgService = consumptionLpgService;
        this.chargeLpgService = chargeLpgService;
    }

    @Scheduled(cron = "0 0 23 * * ?")//每天23点执行一次
    public void configureTasks() throws Exception{
        log.info("执行静态定时任务时间: {}" , LocalDateTime.now());
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String today = dateFormat.format(calendar.getTime());

        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.valueOf((calendar.get(Calendar.MONTH) + 1));
        String day = String.valueOf(calendar.get(Calendar.DATE));
        Integer date = Integer.valueOf(today);

        Map<String, Object> waterProgramme = chargeLpgService.getProgramme();
        BigDecimal price = (BigDecimal) waterProgramme.get("price");
        List<Map<String, Object>> todayConsumptions = consumptionLpgService.getDayConsumption(year, month, day);
        List<FeeLpg> list = new LinkedList<>();
        for (Map<String, Object> todayConsumption : todayConsumptions){
            String dept = (String) todayConsumption.get("dept");
            BigDecimal consumption = new BigDecimal(String.valueOf(todayConsumption.get("consumption")));
            BigDecimal result = price.multiply(consumption).setScale(2, RoundingMode.HALF_UP);
            FeeLpg feeLpg = new FeeLpg();
            feeLpg.setFee(result).setDept(dept).setYear(year).setMonth(month).setDay(day).setDate(date);
            list.add(feeLpg);
        }
        log.info("即将插入的【LPG费】数据: {}" , list);
        feeLpgService.saveBatch(list);
    }
    
}
